package com.admin.service.impl;

import com.admin.pojo.UserInfo;
import com.admin.dao.UserInfoDao;
import com.admin.service.UserInfoService;
import com.admin.util.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author rock
 * @since 2025-06-03 04:58:32
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoDao, UserInfo> implements UserInfoService {

    @Resource
    UserInfoDao userInfoDao;
    @Autowired
    JavaMailSender sender;

    public R register(UserInfo userInfo) {
        int insert = userInfoDao.insert(userInfo);
        if (insert>0)return R.ok("注册成功");
        else return R.fail("注册失败");
    }


    public R sendCode(String email, HttpServletRequest request) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.eq("email", email);
        UserInfo userInfo = userInfoDao.selectOne(queryWrapper);
        if (userInfo==null) {
            return R.fail("邮箱不存在");
        }
        SimpleMailMessage message = new SimpleMailMessage();
        try {
            //收件人
            message.setTo(email);
            //发件人
            message.setFrom("3112745257@qq.com");

            message.setSubject("xx系统验证码");
            int code = (int)(Math.random() * 100000);
            message.setText("验证码为"+code);
            //发送邮件
            sender.send(message);
            //验证码失效时间
            request.getSession().setMaxInactiveInterval(60);

            request.getSession().setAttribute("code",code);

            return R.ok("验证码发送成功");
        }catch (Exception e){
            e.printStackTrace();
            return R.fail("验证码发送失败");
        }


    }


    public R loginCode(String email, String code, HttpServletRequest request) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.eq("email", email);
        UserInfo userInfo = userInfoDao.selectOne(queryWrapper);
        if (userInfo==null) {
            return R.fail("用户不存在");
        }
        //记录用户名
        request.getSession().setAttribute("userName",userInfo.getUserName());
        //获取session里的验证码
        Object c = request.getSession().getAttribute("code");
        if(c==null) {
            return R.fail("验证码过期重新发送");
        }
        if(code.equals(c.toString())) {
            return R.ok(userInfo.getUserName(),"登录成功");
        } else {
            return R.fail("登录失败");
        }
    }
}
